package com.xiechuang.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @Description: AES加解密算法助手
 * @Author: xiechuang
 * @Date: 2023/1/11
 */
public class AESHelper {

    private static final Logger logger = LoggerFactory.getLogger(AESHelper.class);
    private static final String CLASS_NAME = AESHelper.class.getName();
    // 默认的编码
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final String KEY_ALGORITHM = "AES";
    // 默认的加密算法
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    /**
     * AES加密
     *
     * @param content  要加密的内容
     * @param password 加密使用的密钥
     * @return 加密后的字符串
     */
    public static String encrypt(String content, String password) {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(128, random);
            SecretKey secretKey = keyGenerator.generateKey();
            SecretKeySpec key = new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);// 创建密码器
            byte[] byteContent = content.getBytes(DEFAULT_CHARSET);
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return Base64.getUrlEncoder().encodeToString(result).replaceAll("=", "");
        } catch (Exception e) {
            logger.error(CLASS_NAME + "：", e);
        }
        return null;
    }

    /**
     * AES解密
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @return 解密后的字符串
     */
    public static String decrypt(String content, String password) {
        try {
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(password.getBytes());
            byte[] data = Base64.getUrlDecoder().decode(content);
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(128, random);
            SecretKey secretKey = keyGenerator.generateKey();
            SecretKeySpec key = new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
            // 创建密码器
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            // 初始化
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] result = cipher.doFinal(data);
            return new String(result, DEFAULT_CHARSET);
        } catch (Exception e) {
            logger.error(CLASS_NAME + "：", e);
        }
        return null;
    }

}
